package com.sskj.uboex.ui.activity;


import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.MoreLessBean;
import com.sskj.lib.bean.SelfCoinBean;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.model.room.SelfCoinBeanViewModel;
import com.sskj.lib.widget.KChartPop;
import com.sskj.uboex.R;
import com.sskj.uboex.component.DaggerUserDataComponent;
import com.sskj.uboex.presenter.MarketActivityPresenter;
import com.sskj.uboex.ui.fragment.ChartFragment;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.APP_MARKET_NEW)//K线
public class MarketActivity extends BaseActivity<MarketActivityPresenter> {

    @BindView(R.id.marketTab)
    TabLayout mTablayout;
    @BindView(R.id.tvParam)
    TextView tvParam;
    @BindView(R.id.tvUSDT)
    TextView tvUSDT;

    @BindView(R.id.market_more)
    TextView marketMore;
    @BindView(R.id.marker_less)
    TextView markerLess;

    @BindView(R.id.tvCNY)
    TextView tvCNY;
    @BindView(R.id.tvRate)
    TextView tvRate;
    @BindView(R.id.tvHigh)
    TextView tvHigh;
    @BindView(R.id.tvLow)
    TextView tvLow;
    @BindView(R.id.frameLayoutK)
    FrameLayout frameLayoutK;
    @BindView(R.id.ivSelfChoose)
    ImageView ivSelfChoose;
    @BindView(R.id.llSelfChoose)
    LinearLayout llSelfChoose;
    @BindView(R.id.llSelfChooseList)
    LinearLayout llSelfChooseList;
    private KChartPop kChartPop;
    private boolean isUpToggle;
    private ArrayList<ChartFragment> fragmentList = new ArrayList<>();
    String[] goodsType = {"minute", "minute5", "minute15", "minute30", "minute60", "day"};

    private boolean isDownToggle;
    private int currentIndex;
    @Autowired
    String code;
    @Inject
    SelfCoinBeanViewModel selfCoinBeanViewModel;
    private boolean isSelfCheck = false;
    private SelfCoinBean selfCoinBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_market;
    }

    @Override
    public MarketActivityPresenter getPresenter() {
        return new MarketActivityPresenter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(StockCoinBean.StockProductVOBean stockCoinBean) {
        if (stockCoinBean.getCode().equals(code)) {

            tvUSDT.setText(stockCoinBean.getPrice());
            tvCNY.setText(String.format("≈%scny", stockCoinBean.getCnyPrice()));
            tvRate.setText(stockCoinBean.getChangeRate());
            tvHigh.setText(stockCoinBean.getHigh());
            tvLow.setText(stockCoinBean.getLow());
            if (stockCoinBean.isUp()) {
                tvUSDT.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_ff3));
                tvRate.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_ff3));
            } else {
                tvUSDT.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_05c));
                tvRate.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_05c));
            }

        }
    }

    @Override
    protected void initData() {
        mPresenter.getProduct(code);
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        selfCoinBeanViewModel.getUsers().observe(this, selfCoinBeans -> {
            if (selfCoinBeans != null && selfCoinBeans.size() > 0) {
                isSelfCheck = false;
                Flowable.fromIterable(selfCoinBeans)
                        .filter(selfCoinBean -> selfCoinBean.getCode().equals(code))
                        .subscribe(selfCoinBean -> {
                            this.selfCoinBean = selfCoinBean;
                            isSelfCheck = true;
                            ivSelfChoose.setImageDrawable(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.app_icon_self_choose_check));
                        });
                if (!isSelfCheck) {
                    ivSelfChoose.setImageDrawable(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.app_icon_zixuan));
                }
            } else {
                isSelfCheck = false;
                ivSelfChoose.setImageDrawable(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.app_icon_zixuan));

            }
        });
        ClickUtil.click(llSelfChoose, () -> {
            if (isSelfCheck) {
                selfCoinBeanViewModel.delete(selfCoinBean);
            } else {
                SelfCoinBean selfCoinBean = new SelfCoinBean();
                selfCoinBean.setCode(code);
                selfCoinBeanViewModel.insert(selfCoinBean);
            }
        });
        ClickUtil.click(marketMore, () -> {
            RxBus.getDefault().post(new MoreLessBean(true, code));
            finish();
        });
        ClickUtil.click(markerLess, () -> {
            RxBus.getDefault().post(new MoreLessBean(false, code));
            finish();
        });
        ClickUtil.click(llSelfChooseList, () -> {
            ARouter.getInstance().build(RConfig.APP_SELF_CHOOSE).navigation();
        });
        setTitle(code);
        initTab();
        initFive();
        initProfile();
        ClickUtil.click(tvParam, () -> {
            if (kChartPop == null) {
                kChartPop = new KChartPop(this);
                View contentView = kChartPop.getContentView();
                TextView tvMa = contentView.findViewById(R.id.tvMa);
                TextView tvBoll = contentView.findViewById(R.id.tvBoll);
                TextView tvMacd = contentView.findViewById(R.id.tvMacd);
                TextView tvKdj = contentView.findViewById(R.id.tvKdj);
                TextView tvRsi = contentView.findViewById(R.id.tvRsi);
                TextView tvWr = contentView.findViewById(R.id.tvWr);
                ImageView ivUpToggle = contentView.findViewById(R.id.ivUpToggle);
                ImageView ivDownToggle = contentView.findViewById(R.id.ivDownToggle);
                ClickUtil.click(tvMa, () -> {
                    fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().setMainDrawMaShow();
                    ivUpToggle.setImageResource(R.mipmap.see);
                    kChartPop.dismiss();
                });
                ClickUtil.click(tvBoll, () -> {
                    fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().setMainDrawBollShow();
                    ivUpToggle.setImageResource(R.mipmap.see);
                    kChartPop.dismiss();

                });
                ClickUtil.click(ivUpToggle, () -> {
                    if (isUpToggle) {
                        isUpToggle = false;
                        ivUpToggle.setImageResource(R.mipmap.unsee);

                        fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().setMainDrawNoneShow();
                    } else {
                        isUpToggle = true;
                        ivUpToggle.setImageResource(R.mipmap.see);
                        fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().setMainDrawMaShow();
                    }
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvMacd, () -> {
                    fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().changeMACD();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvKdj, () -> {
                    fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().changeKDJ();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvRsi, () -> {
                    fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().changeRSI();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvWr, () -> {
                    fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().changeWR();
                    kChartPop.dismiss();

                });
                ClickUtil.click(ivDownToggle, () -> {
                    if (isDownToggle) {
                        isDownToggle = false;
                        ivDownToggle.setImageResource(R.mipmap.unsee);

                        fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().setDrawDown(isDownToggle);
                    } else {
                        isDownToggle = true;
                        ivDownToggle.setImageResource(R.mipmap.see);

                        fragmentList.get(mTablayout.getSelectedTabPosition()).getKChartView().setDrawDown(isDownToggle);
                    }
                    kChartPop.dismiss();

                });
                kChartPop.setBackground(0);
            }
            if (kChartPop.isShowing()) {
                kChartPop.dismiss();
            } else {
                kChartPop.showPopupWindow(tvParam);
            }
        });
    }

    private void initFive() {
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayoutFive, (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_FIVE).withString(Constans.CODE, code).navigation())
                .commitNowAllowingStateLoss();
    }

    private void initProfile() {
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayoutProfile, (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_PROFILE).navigation())
                .commitNowAllowingStateLoss();
    }

    private void initTab() {
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        mTablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        selectTab(0);
    }

    /**
     * k线切换
     *
     * @param index
     */
    private void selectTab(int index) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ChartFragment minuteFragment = fragmentList.get(index);
        ChartFragment currentFragment = fragmentList.get(currentIndex);
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }
        if (minuteFragment == null) {
            if (index == 0) {
                minuteFragment = ChartFragment.newInstance(code, goodsType[index], false);
            } else {
                minuteFragment = ChartFragment.newInstance(code, goodsType[index], true);
            }
            fragmentList.set(index, minuteFragment);
            ft.add(R.id.frameLayoutK, minuteFragment);
        } else {
            ft.show(minuteFragment);
        }
        ft.commitNowAllowingStateLoss();
        currentIndex = index;
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }


}
